package com.liu.usky.rlzp.uskyrlzp.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class R {
	
	public static String OK(Object object) throws JsonProcessingException {
		return OK(null,object);
	}
	
	public static String OK(String msg,Object object) throws JsonProcessingException {
	return COM(HttpStatus.OK.value(),msg,object);
	}
	
	public static String FAILURE(String msg,Object object) throws JsonProcessingException {
		return COM(HttpStatus.UNAUTHORIZED.value(),msg,object);
	}
	public static String COM(Integer code, String msg,Object object) throws JsonProcessingException {
		ObjectMapper re = new ObjectMapper();
		Map<String,Object> map = new HashMap<>();
		map.put("code", code);
		map.put("msg", msg);
		map.put("data", object);
		return re.writeValueAsString(map);
	}
	
	/**
	 * 获取属性名数组
	 * @param o
	 * @return
	 */
	private String[] getFiledName(Object o) {
		Field[] declaredFields = o.getClass().getDeclaredFields();
		String[] filedNames = new String[declaredFields.length];
		for (int i = 0; i < filedNames.length; i++) {
			filedNames[i] = declaredFields[i].getName();
		}
		return filedNames;
	}
	
	private static Object getFieldValueByName(String fieldName, Object o) {
		try {
			String firstLetter  = fieldName.substring(0, 1).toUpperCase();
			String getter = "get" + firstLetter + fieldName.substring(1);
			Method method = o.getClass().getMethod(getter, new Class[] {});
			Object value = method.invoke(o, new Object[] {});
			return value;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/** 
	    * 获取属性类型(type)，属性名(name)，属性值(value)的map组成的list 
	    * */  
	   private static Map<String,Object> getFiledsInfo(Object o){  
		   SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		   String typeName = o.getClass().getTypeName();
		    Field[] fields=o.getClass().getDeclaredFields();  
	        Map<String,Object> result = new HashMap<>(); 
		    for(int i=0;i<fields.length;i++){  
		    	String type = fields[i].getType().toString();
		    	result.put("name", fields[i].getName());  
		    	if(type.equals(Date.class.getTypeName())) {
		    		result.put("value", sp.format((Date)getFieldValueByName(fields[i].getName(), o)));  
		    	}else {
		    		result.put("value", getFieldValueByName(fields[i].getName(), o));  
		    	}
		    }  
		    return result;  
	   }  
	   /** 
	    * 获取对象的所有属性值，返回一个对象数组 
	    * */  
	   public Object[] getFiledValues(Object o){  
		    String[] fieldNames=this.getFiledName(o);  
		    Object[] value=new Object[fieldNames.length];  
		    for(int i=0;i<fieldNames.length;i++){  
		        value[i]=this.getFieldValueByName(fieldNames[i], o);  
		    }  
		    return value;  
	   } 
	
}
